import paper from 'paper'
import { BaseAnno, BaseTool } from './base'

const local = {
  prevSelection: null,
}

function deselect() {
  if (local.prevSelection) {
    const item = local.prevSelection.path || local.prevSelection
    // item.bounds.selected = false
    item.selected = false
    local.prevSelection.selected = false
    local.prevSelection = null
  }
}

function onMouseDown(event) {
  deselect()
  const result = paper.project.hitTest(event.point, {
    tolerance: 4,
    fill: true,
    stroke: true,
    segments: true,
  })
  let selection = result && result.item
  if (selection) {
    const handle = result.type === 'segment'
    selection.bounds.selected = !handle
    if (handle) selection = result.segment
    selection.selected = true
  }
  local.prevSelection = selection
  return
}

function onMouseUp(event) {
  return
}

function onMouseMove(event) {
  return
}

function onMouseDrag(event) {
  return
}

function onActivate(event) {
  //
}
function onDeactivate(event) {
  deselect()
}

export default class SelectTool extends BaseTool {
  constructor(options) {
    super(options)
    this.onMouseDown = onMouseDown.bind(this)
    this.onMouseUp = onMouseUp.bind(this)
    this.onMouseMove = onMouseMove.bind(this)
    this.onMouseDrag = onMouseDrag.bind(this)
    this.onActivate = onActivate.bind(this)
    this.onDeactivate = onDeactivate.bind(this)
  }

  static get meta() {
    return {
      icon: 'el-icon-search',
      desc: '矩形框',
    }
  }

  get meta() {
    return { ...SelectTool.meta, name: this.name }
  }
}

// this.moveHitOptions = {
//   match: (hitResult) => {
//     if (hitResult && hitResult.type === 'pixel') return false
//     if (
//       hitResult &&
//       hitResult.item &&
//       (hitResult.item.textObject || hitResult.item.markType === 'point' || hitResult.item.markType === 'rectPoint1')
//     ) {
//       return true
//     }
//     return false
//   },
//   segments: true,
//   stroke: true,
//   bounds: true,
//   center: true,
//   tolerance: 4,
// }

// this.clickHitOptions = {
//   match: (hitResult) => {
//     if (hitResult && hitResult.type === 'pixel') return false
//     if (hitResult && hitResult.item && hitResult.item.textObject) {
//       return true
//     }
//     return false
//   },
//   segments: true,
//   stroke: true,
//   bounds: true,
//   center: true,
//   tolerance: 4,
// }
